package net.htjs.juc.twophaseterminate;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 两阶段结束
 * balking模式
 */
@Slf4j
public class TwoPhaseTerminateVolatile {

    public static void main(String[] args) {
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        try {
            TimeUnit.SECONDS.sleep(5);
            twoPhaseTermination.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Slf4j
    static class TwoPhaseTermination {
        private volatile boolean stop = false;
        private Thread monitor;

        //启动监控线程
        public void start() {
            monitor = new Thread(() ->{
                while(true) {
                    Thread thread = Thread.currentThread();
                    if(stop) {
                        log.info("料理后事");
                        break;
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                        log.info("执行监控记录");
                    } catch (InterruptedException e) {
                        log.info("打断");
                    }
                }
            }, "Monitor");
            monitor.start();
        }

        //结束监控线程
        public void stop() {
            stop = true;
            monitor.interrupt();
        }
    }

}
